<template>
  <view class="cart-container">
    <!-- 当购物车有商品时显示商品列表 -->
    <view v-if="cartListArray.length > 0">
      <view v-for="(storeCart, index) in groupedCartList" :key="index" class="store-cart-box">
        <view class="cart-header">
          <view class="select-all">
            <checkbox :checked="isAllSelected(storeCart[0].storeId)" @click="toggleSelectAll(storeCart[0].storeId)"/>全选
          </view>
          <view class="clear-cart" @click="clearStoreCart(storeCart[0].storeId)">清空购物车</view>
        </view>
        
        <view class="store-info">
          <text class="store-name">{{ getStoreName(storeCart[0].storeId) }}</text>
        </view>
        
        <view v-for="(item, itemIndex) in storeCart" :key="itemIndex" class="product-item">
          <view class="product-left">
            <checkbox :checked="item.selected" @click="toggleSelectItem(item)"/>
            <image :src="item.imgUrl" class="product-image"></image>
          </view>
          <view class="product-right">
            <text class="product-name">{{ item.name }}</text>
            <text class="product-sales">月售 {{ item.sales }} 件</text>
            <view class="product-price">
              <text class="current-price">¥{{ item.price }}</text>
              <text class="original-price">¥{{ item.oldPrice }}</text>
            </view>
            <view class="quantity-control">
              <text class="quantity-btn" @click="decreaseQuantity(item)">-</text>
              <text class="quantity-number">{{ item.quantity }}</text>
              <text class="quantity-btn" @click="increaseQuantity(item)">+</text>
            </view>
          </view>
        </view>
        
        <view class="store-footer">
          <view class="store-total">
            总计：¥{{ calculateStoreTotal(storeCart[0].storeId) }}
          </view>
          <view class="checkout-btn" @click="checkoutStore(storeCart[0].storeId)">
            去结算
          </view>
        </view>
      </view>
    </view>
    <!-- 当购物车无商品时显示"购物车为空" -->
    <view v-else class="empty-cart-tip">
      <text>购物车为空</text>
    </view>
  </view>
</template>

<script>
import config from "@/config.js";

export default {
  data() {
    return {
      cartList: {}, // 改为对象格式，与店铺页面一致
      stores: [],
      isLoading: true
    };
  },
  created() {
    this.initData();
  },
  onShow() {
    this.loadCartFromLocalStorage();
  },
  computed: {
    // 将对象格式的购物车转换为数组格式，便于渲染
    cartListArray() {
      return Object.values(this.cartList).flat();
    },
    // 分组
    groupedCartList() {
      const grouped = {};
      this.cartListArray.forEach(item => {
        if (!grouped[item.storeId]) {
          grouped[item.storeId] = [];
        }
        grouped[item.storeId].push(item);
      });
      return Object.values(grouped);
    }
  },
  methods: {
    initData() {
      this.fetchAllStores()
       .then(() => {
          this.isLoading = false;
        })
       .catch(error => {
          console.error('初始化数据出错:', error);
          this.isLoading = false;
        });
    },

    fetchAllStores() {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${config.api_host}super`,
          success: (res) => {
            this.stores = res.data;
            resolve();
          },
          fail: (err) => {
            console.error('获取店铺信息出错:', err);
            reject(err);
          }
        });
      });
    },

   loadCartFromLocalStorage() {
     try {
       const savedCart = wx.getStorageSync('cartList') || {};
       // 初始化每个店铺的购物车商品选中状态
       Object.keys(savedCart).forEach(storeId => {
         savedCart[storeId] = savedCart[storeId].map(item => ({
          ...item,
           selected: item.selected!== undefined? item.selected : true
         }));
       });
       this.cartList = savedCart;
     } catch (error) {
       console.error('加载购物车数据失败:', error);
       this.cartList = {};
     }
   },

    getStoreName(storeId) {
      if (!this.stores || this.stores.length === 0) {
        return '加载中...';
      }

      const store = this.stores.find(item => item._id === storeId);
      return store? store.name : '未知店铺';
    },

 saveCartListToLocalStorage() {
   try {
     wx.setStorageSync('cartList', this.cartList);
   } catch (e) {
     console.error('存储购物车数据失败:', e);
   }
 },

    isAllSelected(storeId) {
      const storeItems = this.cartList[storeId] || [];
      if (storeItems.length === 0) return false;
      return storeItems.every(item => item.selected);
    },

    toggleSelectAll(storeId) {
      const shouldSelectAll =!this.isAllSelected(storeId);
      this.cartList[storeId] = this.cartList[storeId].map(item => ({
       ...item,
        selected: shouldSelectAll
      }));
      this.saveCartListToLocalStorage();
    },

    toggleSelectItem(item) {
      const storeCart = this.cartList[item.storeId] || [];
      const updatedCart = storeCart.map(cartItem => {
        if (cartItem._id === item._id) {
          return {...cartItem, selected:!cartItem.selected};
        }
        return cartItem;
      });
      this.$set(this.cartList, item.storeId, updatedCart);
      this.saveCartListToLocalStorage();
    },

    clearStoreCart(storeId) {
      uni.showModal({
        title: '提示',
        content: '确定要清空该店铺购物车吗？',
        success: (res) => {
          if (res.confirm) {
            this.$delete(this.cartList, storeId);
            this.saveCartListToLocalStorage();
          }
        }
      });
    },

    increaseQuantity(item) {
      const storeCart = this.cartList[item.storeId] || [];
      const updatedCart = storeCart.map(cartItem => {
        if (cartItem._id === item._id) {
          return {...cartItem, quantity: cartItem.quantity + 1};
        }
        return cartItem;
      });
      this.$set(this.cartList, item.storeId, updatedCart);
      this.saveCartListToLocalStorage();
    },

    decreaseQuantity(item) {
      const storeCart = this.cartList[item.storeId] || [];
      if (item.quantity <= 1) {
        const updatedCart = storeCart.filter(cartItem => cartItem._id!== item._id);
        if (updatedCart.length === 0) {
          this.$delete(this.cartList, item.storeId);
        } else {
          this.$set(this.cartList, item.storeId, updatedCart);
        }
      } else {
        const updatedCart = storeCart.map(cartItem => {
          if (cartItem._id === item._id) {
            return {...cartItem, quantity: cartItem.quantity - 1};
          }
          return cartItem;
        });
        this.$set(this.cartList, item.storeId, updatedCart);
      }
      this.saveCartListToLocalStorage();
    },
    //计算价格
    calculateStoreTotal(storeId) {
      const storeItems = this.cartList[storeId] || [];
      const selectedItems = storeItems.filter(item => item.selected);
      return selectedItems.reduce((total, item) => 
        total + (item.price * item.quantity), 0
      ).toFixed(2);
    },

    checkoutStore(storeId) {
      const storeItems = this.cartList[storeId] || [];
      const selectedItems = storeItems.filter(item => item.selected);
      if (selectedItems.length === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        });
        return;
      }
      const cartListString = encodeURIComponent(JSON.stringify(selectedItems));
      uni.navigateTo({
        url: `/pages/address/Addlist?cartList=${cartListString}`
      });
    }
  }
};
</script>

<style scoped>
.cart-container {
  padding: 15px;
  background-color: #f5f5f5;
  min-height: 100vh;
  font-family: Arial, sans-serif;
}

.store-cart-box {
  background-color: white;
  border-radius: 10px;
  margin-bottom: 15px;
  padding: 10px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 5px;
  border-bottom: 1px solid #f0f0f0;
}

.select-all {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.clear-cart {
  font-size: 14px;
  color: #666;
}

.store-info {
  padding: 10px 5px;
}

.store-name {
  font-size: 16px;
  font-weight: bold;
}

.product-item {
  display: flex;
  padding: 10px 5px;
  border-bottom: 1px solid #f0f0f0;
}

.product-left {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-left: 10px;
  border-radius: 4px;
}

.product-right {
  flex: 1;
}

.product-name {
  font-size: 15px;
  color: #333;
  display: block;
  margin-bottom: 5px;
}

.product-sales {
  font-size: 12px;
  color: #999;
  display: block;
  margin-bottom: 5px;
}

.product-price {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.current-price {
  font-size: 16px;
  color: #ff6700;
  margin-right: 10px;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.quantity-btn {
  width: 25px;
  height: 25px;
  line-height: 25px;
  text-align: center;
  border: 1px solid #ddd;
  font-size: 16px;
  border-radius: 4px;
}

.quantity-number {
  width: 30px;
  text-align: center;
  font-size: 14px;
}

.store-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 5px;
  margin-top: 10px;
}

.store-total {
  font-size: 16px;
  color: #ff6700;
  font-weight: bold;
}

.checkout-btn {
  background-color: #ff6700;
  color: white;
  padding: 8px 20px;
  border-radius: 20px;
  font-size: 14px;
}

.empty-cart-tip {
  font-size: 16px;
  color: #999;
  text-align: center;
  margin-top: 50%;
  transform: translateY(-50%);
}
</style>    